﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Steeltoe.Common.Discovery;
using Steeltoe.Discovery;

namespace consumer.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ValuesController : ControllerBase
    {

        DiscoveryHttpClientHandler _handler;
        private const string PROVIDER_URL = "https://provider/values";

        private readonly ILogger<ValuesController> _logger;

        public ValuesController(ILogger<ValuesController> logger, IDiscoveryClient client)
        {
            _logger = logger;
            _handler = new DiscoveryHttpClientHandler(client);
        }

        [HttpGet]
        public IEnumerable<String> Get([FromServices]IHostEnvironment env)
        {
            var ip = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
            var ipstrs = ip.Select(x => x.ToString());
            //var ip = System.Net.IPAddress.;
            return new List<string>() { "consumer", env.EnvironmentName, ipstrs.Aggregate((x, y) => x + "," + y)};
        }

        [HttpGet("getprovider")]
        public async Task<string> RandomFortuneAsync()
        {
            var client = GetClient();
            return await client.GetStringAsync(PROVIDER_URL);
        }


        private HttpClient GetClient()
        {
            // WARNING: do NOT create a new HttpClient for every request in your code
            // -- you may experience socket exhaustion if you do!
            var client = new HttpClient(_handler, false);
            return client;
        }
    }
}
